{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from email.header import Header\n",
    "import smtplib\n",
    "from email.mime.multipart import MIMEMultipart\n",
    "from email.mime.application import MIMEApplication\n",
    "from email.mime.text import MIMEText"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "def SendEmail(emailcontent):#发送邮件的函数\n",
    "    asender ='1261520571@qq.com'#发件邮箱\n",
    "    areceiver='15211097884@163.com' #收件邮箱\n",
    "    asmtpserver = 'smtp.qq.com' #'smtp.qq.com'#发件邮箱smtp地址\n",
    "    ausername = '1261520571@qq.com'#'#发件邮箱用户名\n",
    "    apassword = 'ehevkdghepqxhfjd' #'umgqwturdjycbagg'#发件邮箱密码\n",
    "    \n",
    "    msgroot = MIMEMultipart('related')\n",
    "    msgroot['Subject'] = Header('Trading Signal')#邮件标题\n",
    "    msgroot['to'] = areceiver\n",
    "    msgroot['from']\t= asender \n",
    "    \n",
    "    thebody=MIMEText('condition met '+ emailcontent+',traded','plain', 'UTF-8') #邮件正文\n",
    "    thebody[\"Accept-Language\"]=\"zh-CN\"\n",
    "    thebody[\"Accept-Charset\"]=\"UTF-8\" #\"UTF-8\"\n",
    "    msgroot.attach(thebody)\n",
    "    \n",
    "    asmtp = smtplib.SMTP()\n",
    "    asmtp.connect(asmtpserver, 25)\n",
    "    asmtp.login(ausername, apassword)\n",
    "    asmtp.sendmail(asender, areceiver.split(','), msgroot.as_string())\n",
    "    asmtp.quit()\n",
    "    print(\"mail sending done.\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "mail sending done.\n"
     ]
    }
   ],
   "source": [
    "emailcontent = \"买入 上海机场\"\n",
    "SendEmail(emailcontent)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 以下为在joinquant里实现的代码"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 导入函数库\n",
    "from jqdata import *\n",
    "from email.header import Header\n",
    "import smtplib\n",
    "from email.mime.multipart import MIMEMultipart\n",
    "from email.mime.application import MIMEApplication\n",
    "from email.mime.text import MIMEText\n",
    "import numpy as np\n",
    "\n",
    "def SendEmail(emailcontent):#发送邮件的函数\n",
    "    asender ='1261520571@qq.com'#发件邮箱\n",
    "    areceiver='15211097884@163.com' #收件邮箱\n",
    "    asmtpserver = 'smtp.qq.com' #'smtp.qq.com'#发件邮箱smtp地址\n",
    "    ausername = '1261520571@qq.com'#'#发件邮箱用户名\n",
    "    apassword = 'ehevkdghepqxhfjd' #'umgqwturdjycbagg'#发件邮箱密码\n",
    "    \n",
    "    msgroot = MIMEMultipart('related')\n",
    "    msgroot['Subject'] = Header('交易提醒') #邮件标题\n",
    "    msgroot['to'] = areceiver\n",
    "    msgroot['from']\t= asender \n",
    "    \n",
    "    thebody=MIMEText(emailcontent,'plain', 'UTF-8') #邮件正文\n",
    "    thebody[\"Accept-Language\"]=\"zh-CN\"\n",
    "    thebody[\"Accept-Charset\"]=\"UTF-8\" #\"UTF-8\"\n",
    "    msgroot.attach(thebody)\n",
    "    \n",
    "    asmtp = smtplib.SMTP()\n",
    "    asmtp.connect(asmtpserver, 25)\n",
    "    asmtp.login(ausername, apassword)\n",
    "    asmtp.sendmail(asender, areceiver.split(','), msgroot.as_string())\n",
    "    asmtp.quit()\n",
    "    print(\"mail sending done.\")\n",
    "\n",
    "# 初始化函数，设定基准等等\n",
    "def initialize(context):\n",
    "    # 设定沪深300作为基准\n",
    "    set_benchmark('000300.XSHG')\n",
    "    # 开启动态复权模式(真实价格)\n",
    "    set_option('use_real_price', True)\n",
    "    # 输出内容到日志 log.info()\n",
    "    log.info('初始函数开始运行且全局只运行一次')\n",
    "\n",
    "    # 使用数组来表示当前的状态，1表时已入场，0表时未入场\n",
    "    g.stock_state = np.array([0,0,0,0,0,1,0])\n",
    "    g.fund_state = np.array([1,1,1])\n",
    "    # 跟踪的股票：上海机场、中国国旅、五粮液、恒瑞医药、通策医疗、中顺洁柔、昭衍新药（g.为全局变量）\n",
    "    g.stock_security = ['600009.XSHG', '601888.XSHG', '000858.XSHE', '600276.XSHG', '600763.XSHG', '002511.XSHE', '603127.XSHG']\n",
    "    # 要操作的基金：半导体50，通信ETF，医疗ETF\n",
    "    g.fund_security = ['512760.XSHG', '515880.XSHG', '512170.XSHG']\n",
    "\n",
    "    # 运行函数（reference_security为运行时间的参考标的；传入的标的只做种类区分，因此传入'000300.XSHG'或'510300.XSHG'是一样的）\n",
    "    # 收盘后运行\n",
    "    run_daily(after_market_close, time='after_close', reference_security='000300.XSHG')\n",
    "\n",
    "## 收盘后运行函数\n",
    "def after_market_close(context):\n",
    "    log.info(str('函数运行时间(after_market_close):'+str(context.current_dt.time())))\n",
    "    #得到当天所有成交记录\n",
    "    trades = get_trades()\n",
    "    stock_list = g.stock_security\n",
    "    \n",
    "    for i in range(len(stock_list)):\n",
    "        close_data = get_bars(stock_list[i], count=22, unit='1d', fields=['close'])\n",
    "        # 取得过去20天的平均价格\n",
    "        MA20_current = close_data['close'][2:].mean()\n",
    "        MA20_last = close_data['close'][1:21].mean()\n",
    "        MA20_llast = close_data['close'][:20].mean()\n",
    "        \n",
    "        if MA20_current > MA20_last and MA20_last < MA20_llast :\n",
    "            if g.stock_state[i] == 0:\n",
    "                g.stock_state[i] = 1\n",
    "                emailcontent = \"买入 {}, 当前价格: {}\"\\\n",
    "                    .format(get_security_info(stock_list[i]).display_name,close_data['close'][-1])\n",
    "                # print(emailcontent)\n",
    "                SendEmail(emailcontent)\n",
    "            else:\n",
    "                emailcontent = \"更新 {} 的止盈点, 当前价格: {}\"\\\n",
    "                    .format(get_security_info(stock_list[i]).display_name,close_data['close'][-1])\n",
    "                # print(emailcontent)\n",
    "                SendEmail(emailcontent)\n",
    "        \n",
    "    fund_list = g.fund_security\n",
    "    for i in range(len(fund_list)):\n",
    "        close_data = get_bars(fund_list[i], count=22, unit='1d', fields=['close'])\n",
    "        # 取得过去20天的平均价格\n",
    "        MA20_current = close_data['close'][2:].mean()\n",
    "        MA20_last = close_data['close'][1:21].mean()\n",
    "        MA20_llast = close_data['close'][:20].mean()\n",
    "        \n",
    "        if MA20_current > MA20_last and MA20_last < MA20_llast and g.fund_state[i] == 0:\n",
    "            g.fund_state[i] = 1\n",
    "            emailcontent = \"买入 {}, 当前价格: {}\"\\\n",
    "                    .format(get_security_info(fund_list[i]).display_name,close_data['close'][-1])\n",
    "            # print(emailcontent)\n",
    "            SendEmail(emailcontent)\n",
    "        elif close_data['close'][-1] < MA20_current and g.fund_state[i] == 1:\n",
    "            g.fund_state[i] = 0\n",
    "            emailcontent = \"卖出 {}, 当前价格: {}\"\\\n",
    "                    .format(get_security_info(fund_list[i]).display_name,close_data['close'][-1])\n",
    "            # print(emailcontent)\n",
    "            SendEmail(emailcontent)\n",
    "    \n",
    "    for _trade in trades.values():\n",
    "        log.info('成交记录：'+str(_trade))\n",
    "    log.info('一天结束')\n",
    "    log.info('##############################################################')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
